import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/rendering.dart';
import 'package:xvideos/tools_base/debug_log.dart';

class AdaptorTabMenu extends StatefulWidget {
  final int length;
  final int selectIndex;
  final NullableIndexedWidgetBuilder itemBuilder;

  AdaptorTabMenu({
    required this.length,
    required this.selectIndex,
    required this.itemBuilder,
  });

  @override
  State<StatefulWidget> createState() {
    return AdaptorTabMenuState();
  }
}

class AdaptorTabMenuState extends State<AdaptorTabMenu> {
  ScrollController scrollController = ScrollController();
  GlobalKey scrollerKey = GlobalKey();
  List<GlobalKey> keyArr = [];

  @override
  void initState() {
    super.initState();
    for (int i = 0; i < widget.length; i++) {
      keyArr.add(GlobalKey());
    }
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      scrollerToCenter();
    });
  }

  @override
  void didUpdateWidget(covariant AdaptorTabMenu oldWidget) {
    if (widget.length != oldWidget.length) {
      keyArr.clear();
      for (int i = 0; i < widget.length; i++) {
        keyArr.add(GlobalKey());
      }
    }
    if (widget.length != oldWidget.length || widget.selectIndex != oldWidget.selectIndex) {
      WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
        scrollerToCenter();
      });
    }
    super.didUpdateWidget(oldWidget);
  }

  void scrollerToCenter() {
    try {
      double scrollerWidth = getWidthFromKey(scrollerKey);
      if (scrollerWidth <= 0) {
        return;
      }
      double selectPosX = getExposureOffset(keyArr[widget.selectIndex]) ?? 0;
      double curItemWidth = getWidthFromKey(keyArr[widget.selectIndex]);
      if (scrollController.hasClients) {
        double centerX = selectPosX + curItemWidth / 2;
        double moveX = centerX - scrollerWidth / 2;
        moveX = max(0, moveX);
        moveX = min(moveX, scrollController.position.maxScrollExtent);
        scrollController.animateTo(moveX, duration: Duration(milliseconds: 250), curve: Curves.easeInOut);
      }
    } catch (e) {
      debugLog("size失败");
    }
  }

  double getWidthFromKey(GlobalKey key) {
    final RenderObject? box = key.currentContext?.findRenderObject();
    Size? scrollSize = box?.paintBounds.size;
    return scrollSize?.width ?? 0;
  }

  double? getExposureOffset(GlobalKey key) {
    try {
      RenderObject? box = key.currentContext?.findRenderObject();
      RenderAbstractViewport? viewport = RenderAbstractViewport.of(box);
      if (box == null || !box.attached) {
        return null;
      }
      // box 为当前 Item 的 RenderObject
      // alignment 为 0 的时候获得距离起点的相对偏移量
      // 为 1 的时候获得距离终点的相对偏移量。
      final RevealedOffset offsetRevealToTop = viewport.getOffsetToReveal(box, 0.0, rect: Rect.zero, axis: Axis.horizontal);
      return offsetRevealToTop.offset;
    } catch (e) {
      debugLog(e);
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      key: scrollerKey,
      controller: scrollController,
      padding: EdgeInsets.zero,
      scrollDirection: Axis.horizontal,
      children: List.generate(
        widget.length,
        (index) => SizedBox(
          key: keyArr[index],
          child: widget.itemBuilder(context, index),
        ),
      ),
    );
  }
}
